<template>
  <div id="qcResultTable">
    <el-tabs :tab-position="'top'" v-model="activeName" class="qcResultTableTabs">
      <el-tab-pane label="质控物" name="iqcMaterial">
        <vxe-table ref="tabRef1" class="mytable-scrollbar" height="auto" v-loading="mloading" border align="center" :data="iqcMaterialList" :row-config="{ isCurrent: true, isHover: true }" :keyboard-config="{
            isArrow: true,
            isTab: true,
            isEdit: true
          }" :span-method="rowspanMethod" resizable show-overflow>
          <vxe-colgroup title="质控物">
            <vxe-column field="materialName" title="质控物" width="160"></vxe-column>
            <vxe-column field="horizontal" title="水平" width="30"></vxe-column>
            <vxe-column field="manufacturer" title="生产商" width="160"></vxe-column>
            <vxe-column field="method" title="测试方法" width="60"></vxe-column>
          </vxe-colgroup>
          <vxe-colgroup title="质控物累计">
            <vxe-column field="toTalMean" title="靶值" width="50" align="right" header-align="center">
              <template #default="{ row }">
                <span>{{ row.toTalMean.toFixed(4) }}</span>
              </template>
            </vxe-column>
            <vxe-column field="toTalCv" title="CV(%)" width="40" align="right" header-align="center">
              <template #default="{ row }">
                <span>{{ (row.toTalCv * 100).toFixed(2) }}</span>
              </template>
            </vxe-column>
            <vxe-column field="toTalSd" title="SD" width="50" align="right" header-align="center">
              <template #default="{ row }">
                <span>{{ row.toTalSd.toFixed(4) }}</span>
              </template>
            </vxe-column>
          </vxe-colgroup>
          <vxe-colgroup title="质控物批次">
            <vxe-column field="batchNum" title="批号" width="80">
              <template #default="{ row }">
                <span>{{ row.batchNum ? row.batchNum : '' }}</span>
              </template>
            </vxe-column>
            <vxe-column field="enableDate" title="生产日期" width="70">
              <template #default="{ row }">
                <span>{{
                  row.enableDate ? formatDateTime(row.enableDate, 'yyyy-MM-dd') : ''
                }}</span>
              </template>
            </vxe-column>
            <vxe-column field="validDate" title="失效日期" width="70">
              <template #default="{ row }">
                <span>{{ row.validDate ? formatDateTime(row.validDate, 'yyyy-MM-dd') : '' }}</span>
              </template>
            </vxe-column>
          </vxe-colgroup>
          <vxe-colgroup title="本月累计">
            <vxe-column field="mean" title="靶值" width="50" align="right" header-align="center">
              <template #default="{ row }">
                <span>{{ row.mean ? row.mean.toFixed(4) : '' }}</span>
              </template>
            </vxe-column>
            <vxe-column field="cv" title="CV(%)" width="40" align="right" header-align="center">
              <template #default="{ row }">
                <span>{{ row.cv ? (row.cv * 100).toFixed(2) : '' }}</span>
              </template>
            </vxe-column>
            <vxe-column field="sd" title="SD" width="50" align="right" header-align="center">
              <template #default="{ row }">
                <span>{{ row.sd ? row.sd.toFixed(4) : '' }}</span>
              </template>
            </vxe-column>
          </vxe-colgroup>
          <vxe-colgroup title="质控参数">
            <vxe-column field="stageEnableTime" title="启用时间" width="70">
              <template #default="{ row }">
                <span>{{
                  row.stageEnableTime ? formatDateTime(row.stageEnableTime, 'yyyy-MM-dd') : ''
                }}</span>
              </template>
            </vxe-column>
            <vxe-column field="stageDisableTime" title="停用时间" width="70">
              <template #default="{ row }">
                <span>{{
                  row.stageDisableTime ? formatDateTime(row.stageDisableTime, 'yyyy-MM-dd') : ''
                }}</span>
              </template>
            </vxe-column>

            <vxe-column field="stageMean" title="靶值" align="right" width="50" header-align="center">
              <template #default="{ row }">
                <span>{{ row.stageMean ? row.stageMean.toFixed(4) : '' }}</span>
              </template>
            </vxe-column>
            <vxe-column field="stageCV" title="CV(%)" width="40" align="right" header-align="center">
              <template #default="{ row }">
                <span>{{ row.stageCV ? row.stageCV.toFixed(2) : '' }}</span>
              </template>
            </vxe-column>
            <vxe-column field="stageSD" title="SD" width="50" align="right" header-align="center">
              <template #default="{ row }">
                <span>{{ row.stageSD ? row.stageSD.toFixed(4) : '' }}</span>
              </template>
            </vxe-column>
          </vxe-colgroup>
        </vxe-table>
      </el-tab-pane>
      <el-tab-pane label="质控结果" name="iqcMaterialResult" style="height: 100%">
        <el-table ref="tabRef2" v-loading="rloading" row-key="id" :data="iqcResultData.iqcMaterials" :span-method="objectSpanMethod" height="100%">
          <el-table-column prop="name" label="质控物" width="110" align="center" show-overflow-tooltip></el-table-column>
          <el-table-column label="次数" width="40" align="center">
            <template #default="{ row }">
              <el-table row-key="id" :data="row.data" :show-header="false" @cell-click="cellClick" border>
                <el-table-column prop="num" label="次数" width="40" align="center" show-overflow-tooltip></el-table-column>
                <el-table-column v-for="(time, index) in iqcResultData.xdateTimeList" :key="index" width="70" align="right" show-overflow-tooltip>
                  <template v-slot:header>
                    {{ time }}
                  </template>
                  <template #default="{ row }">
                    <div :class="row.resultData[index].isOutControl ? 'isOutControl' : ''">
                      {{ row.resultData[index].result }}
                    </div>
                  </template>
                </el-table-column>
                <el-table-column min-width="1"></el-table-column>
              </el-table>
              <div>
                本月质控个数:
                <span style="color: #67c23a; margin-right: 15px">{{ row.total }}</span>
                其中在控个数:
                <span style="color: #67c23a; margin-right: 15px">{{ row.controlNum }}</span>
                失控个数:
                <span style="color: #f56c6c; margin-right: 15px">{{ row.outControlNum }}</span>
                在控率:
                <span style="color: #67c23a; margin-right: 15px">{{ (row.controlRate * 100).toFixed(2) }}%</span>
                失控率:
                <span style="color: #f56c6c; margin-right: 15px">{{ (row.outControlRate * 100).toFixed(2) }}%</span>
              </div>
            </template>
          </el-table-column>
          <el-table-column width="70" v-for="(time, index) in iqcResultData.xdateTimeList" :key="index" align="right" show-overflow-tooltip>
            <template v-slot:header>
              {{ time }}
            </template>
          </el-table-column>
          <el-table-column min-width="1"></el-table-column>
        </el-table>
      </el-tab-pane>
      <el-tab-pane label="质控总结" name="summaryPane" style="height: 100%">
        <div class="summaryDiv">
          <vxe-form :data="summaryForm" class-name="padding-sm width-100-percentage" title-width="70px">
            <vxe-form-item title="质控月份:" :item-render="{}" field="qcMonth" class-name="width-100-percentage">
              <template #default="{ data }">
                <vxe-input v-model="data.qcMonth" placeholder="选择月份" type="month" valueFormat="yyyy-MM" transfer @change="getQcMaterialSummary"></vxe-input>
              </template>
            </vxe-form-item>

            <vxe-form-item title="质控总结:" :item-render="{}" field="summary" class-name="width-100-percentage">
              <template #default="{ data }">
                <vxe-textarea style="width:50%;" v-model="data.summary" placeholder="请输入质控总结" :autosize="{ minRows: 3, maxRows: 5 }"></vxe-textarea>
              </template>
            </vxe-form-item>
            <vxe-form-item>
              <el-button class="svesuBut" type="primary" @click="saveMaterialSummary()"> 保存 </el-button>
            </vxe-form-item>
          </vxe-form>
        </div>
      </el-tab-pane>

    </el-tabs>
  </div>
</template>
<script lang="ts" setup>
import { ref, defineExpose, reactive, getCurrentInstance, onMounted } from 'vue';
import { VxeMessage, VxeNotifyType } from '@/utils/CommonMessage'; //提示
import { formatDateTime, IsEmpty } from '@/utils/common';
import { VxeTableInstance } from 'vxe-table';
defineExpose({
  getIQCResultList,
  getIQCMaterialsInfoAsync,
  initQcMaterialSummary
});
// 变量定义区
const tabRef1 = ref<VxeTableInstance>();
let { proxy }: any = getCurrentInstance();
const activeName = ref('iqcMaterial');
let iqcResultData: any = reactive({}); //质控物结果
let iqcMaterialList: any = reactive([]);
let mloading = ref(false);
let rloading = ref(false);
const resultForm = reactive({
  rptGroupId: null, //报告单元id
  rptGroupName: '',
  // selectWorkTeam: '', //选中的子工作组id
  insId: null, //仪器
  insName: '',
  insAnsId: null, //仪器项目
  qcItemId: null, //项目
  itemDictId: null,
  ansName: '',
  iqcMaterialIds: [],
  QCDateS: null, //开始时间
  QCDateE: null //结束时间
});

let summaryForm = reactive({
  id: '',
  instrId: '',
  qcMonth: formatDateTime(new Date(), 'yyyy-MM'),
  summary: ''
});

function getIQCMaterialsInfoAsync(val: any, iqcResultForm: any) {
  mloading.value = true;
  iqcMaterialList.length = 0;
  if (iqcResultForm.iqcMaterialIds.length === 0) {
    if (tabRef1.value) {
      tabRef1.value?.reloadData([]);
    }
    mloading.value = false;
    return;
  }
  const url = '/api/qc/qcMaterialItemResult/getIQCMaterialsInfoAsync';
  proxy.$http
    //注意此处的数据条数
    .get(url, {
      params: {
        itemDictId: iqcResultForm.itemDictId,
        materialIds: iqcResultForm.iqcMaterialIds.join(','),
        QCDateS: iqcResultForm.QCDateS,
        QCDateE: iqcResultForm.QCDateE
      }
    })
    .then((res: any) => {
      const resList = [];
      if (res.data && res.data.length > 0) {
        res.data.forEach((item) => {
          if (item.targetDtoList.length > 0) {
            item.targetDtoList.forEach((stage) => {
              resList.push({
                materialId: item.materialId,
                materialName: item.materialName,
                horizontal: item.horizontal,
                manufacturer: item.manufacturer,
                method: item.method,
                mean: item.mean,
                sd: item.sd,
                cv: item.cv,
                toTalMean: item.toTalMean,
                toTalSd: item.toTalSd,
                toTalCv: item.toTalCv,
                batchNum: item.batchNum,
                enableDate: item.enableDate,
                validDate: item.validDate,
                materialTargetId: stage.materialTargetId,
                stageEnableTime: stage.taEnableDate,
                stageDisableTime: stage.stopDate,
                stageMean: stage.mean,
                stageSD: stage.sd,
                stageCV: stage.cv
              });
            });
          } else {
            resList.push({
              materialId: item.materialId,
              materialName: item.materialName,
              horizontal: item.horizontal,
              manufacturer: item.manufacturer,
              method: item.method,
              mean: item.mean,
              sd: item.sd,
              cv: item.cv,
              toTalMean: item.toTalMean,
              toTalSd: item.toTalSd,
              toTalCv: item.toTalCv,
              batchNum: item.batchNum,
              enableDate: item.enableDate,
              validDate: item.validDate
            });
          }
        });
      }
      iqcMaterialList = resList;
      mloading.value = false;
    })
    .catch((err: any) => {
      mloading.value = false;
      console.log(err);
      VxeMessage('获取右侧质控项目表格数据异常', VxeNotifyType.error);
    });
}

let summarySearhForm = reactive({
  instrId: ''
});
function initQcMaterialSummary(iqcResultForm: any) {
  summarySearhForm.instrId = iqcResultForm.insId;
  getQcMaterialSummary();
}

function getQcMaterialSummary() {
  summaryForm.instrId = summarySearhForm.instrId;
  //根据仪器id和质控月份查询质控总结
  const url = '/api/qc/qcMaterialSummary/getQcMaterialSummary';
  proxy.$http
    //注意此处的数据条数
    .get(url, {
      params: {
        instrId: summaryForm.instrId,
        qcMonth: summaryForm.qcMonth
      }
    })
    .then((res: any) => {
      console.log(res);
      if (res && res.status && res.status.code && res.status.code === 200) {
        console.log(res.data);
        if (!IsEmpty(res.data)) {
          setsummaryForm(res.data);
        } else {
          cleansummaryForm();
        }
      } else {
        cleansummaryForm();
      }
    })
    .catch((err: any) => {
      console.log(err);
      VxeMessage('获取右侧质控项目表格数据异常', VxeNotifyType.error);
    });

  console.log(summaryForm);
}
function setsummaryForm(obj: any) {
  summaryForm.id = obj.id;
  summaryForm.instrId = obj.instrId;
  summaryForm.summary = obj.summary;
  summaryForm.qcMonth = obj.qcMonth;
}
function cleansummaryForm() {
  summaryForm.id = '';
  summaryForm.summary = '';
}
function saveMaterialSummary() {
  console.log(summaryForm);

  if (IsEmpty(summaryForm.id)) {
    const url = '/api/qc/qcMaterialSummary/addMaterialSummary';
    const supplier = {
      instrId: summaryForm.instrId,
      qcMonth: summaryForm.qcMonth,
      summary: summaryForm.summary
    };
    proxy.$http
      .post(url, supplier)
      .then((res: any) => {
        VxeMessage('新增成功', VxeNotifyType.success);
        setsummaryForm(res.data);
      })
      .catch((err: any) => {
        VxeMessage('新增失败', VxeNotifyType.error);
      });
  } else {
    // 修改用户
    const url = '/api/qc/qcMaterialSummary/editMaterialSummary';

    const supplier = {
      id: summaryForm.id,
      instrId: summaryForm.instrId,
      qcMonth: summaryForm.qcMonth,
      summary: summaryForm.summary
    };
    proxy.$http
      .post(url, supplier)
      .then((res: any) => {
        VxeMessage('修改成功', VxeNotifyType.success);
        setsummaryForm(res.data);
      })
      .catch((err: any) => {
        VxeMessage('修改失败', VxeNotifyType.error);
      });
  }
}

// 获取质控物结果列表
function getIQCResultList(val: any, iqcResultForm: any) {
  rloading.value = true;
  iqcResultData = {};
  if (iqcResultForm.iqcMaterialIds.length === 0) {
    rloading.value = false;
    return;
  }
  let url = '/api/qc/chart/getResultChartTable2';
  let obj = {
    qcItemId: iqcResultForm.qcItemId,
    itemDictId: iqcResultForm.itemDictId,
    materialIds: iqcResultForm.iqcMaterialIds.join(','),
    QCDateS: iqcResultForm.QCDateS,
    QCDateE: iqcResultForm.QCDateE
  };
  proxy.$http
    .get(url, { params: obj })
    .then((res: any) => {
      if (!IsEmpty(res.data.iqcMaterials)) {
        if (res.data.iqcMaterials.length > 0 && res.data.xdateTimeList.length > 0) {
          res.data.iqcMaterials.forEach((mat) => {
            mat.data.forEach((item) => {
              res.data.xdateTimeList.forEach((time, index) => {
                const newRes = [];
                // 把查询的时间范围和产生质控结果的时间对比。在没有产生结果的时间，对应位置插入 result 为 “-”的值
                const idx = item.resultData.findIndex((result) => {
                  return time === result.time;
                });
                if (idx === -1) {
                  item.resultData.splice(index, 0, {
                    result: '',
                    time
                  });
                } else {
                  const temp = item.resultData[index];
                  item.resultData[index] = item.resultData[idx];
                  item.resultData[idx] = temp;
                }
                // 按 xdateTimeList 返回的 时间排序
              });
            });
          });
          iqcResultData = res.data;
        }
      }
      rloading.value = false;
    })
    .catch((err) => {
      VxeMessage('获取右侧质控项目表格数据异常', VxeNotifyType.error);
      rloading.value = false;
    });
}

function objectSpanMethod({ row, column, rowIndex, columnIndex }) {
  // 把第2列之后的单元格合并
  if (columnIndex === 1) {
    return [1, iqcResultData.xdateTimeList.length + 2]; //+2是因为需要把“次数”列和最后一列（无实际意义，用来防止列表过短）也进行合并
  } else if (columnIndex > 1) {
    return [0, 0];
  }
}

// 合并行
function rowspanMethod({ row, _rowIndex, column, _columnIndex, visibleData }) {
  // 质控物相关列，行合并
  const methodName = [
    ['materialId', 'materialName', 'horizontal', 'manufacturer', 'method', 'mean', 'sd', 'cv', 'batchNum', 'enableDate', 'validDate', 'toTalMean', 'toTalCv', 'toTalSd'], //质控物相关列
    ['materialTargetId', 'taEnableDate', 'stopDate', 'stageMean', 'stageSD', 'stageCV'] //批号相关列
  ];
  let cellValue = row[column.property];

  if (cellValue && methodName[0].includes(column.property)) {
    let prevRow = visibleData[_rowIndex - 1];
    let nextRow = visibleData[_rowIndex + 1];
    if (prevRow && prevRow.materialId === row.materialId) {
      return { rowspan: 0, colspan: 0 };
    } else {
      let countRowspan = 1;
      while (nextRow && nextRow.materialId === row.materialId) {
        nextRow = visibleData[++countRowspan + _rowIndex];
      }
      if (countRowspan > 1) {
        return { rowspan: countRowspan, colspan: 1 };
      }
    }
  }

  if (cellValue && methodName[1].includes(column.property)) {
    let prevRow = visibleData[_rowIndex - 1];
    let nextRow = visibleData[_rowIndex + 1];
    if (prevRow && prevRow.materialTargetId === row.materialTargetId) {
      return { rowspan: 0, colspan: 0 };
    } else {
      let countRowspan = 1;
      while (nextRow && nextRow.materialTargetId === row.materialTargetId) {
        nextRow = visibleData[++countRowspan + _rowIndex];
      }
      if (countRowspan > 1) {
        return { rowspan: countRowspan, colspan: 1 };
      }
    }
  }
}
</script>
<style lang="scss" scoped>
#qcResultTable {
  height: 100%;
  .qcResultTableTabs {
    height: 100%;
    .el-tab-pane {
      height: 100%;
    }

    :deep(.el-tabs__header) {
      margin: 0 0 10px 0 !important;
      padding: 0 0 0 15px !important;
    }
    :deep(.el-tabs__content) {
      padding-right: 10px !important;
    }
    .summaryDiv {
      width: 50%;
      .svesuBut {
        margin-left: 10px;
      }
    }
  }

  :deep(.el-table) {
    .cell,
    td {
      padding: 0;
    }
    th {
      padding: 2px;
    }

    .el-table {
      .cell,
      td {
        padding: 1px;
      }
      .cell.el-tooltip {
        min-width: auto;
      }
      .el-table__body-wrapper {
        overflow-x: hidden;
      }
      .isOutControl {
        color: red;
      }
    }
    .el-table + div {
      border-left: 1px solid #ebeef5;
      border-right: 1px solid #ebeef5;
    }
  }
}
</style>
